package com.ruoyi.framework.security.handle

import com.alibaba.fastjson2.JSON
import com.ruoyi.common.constant.Constants
import com.ruoyi.common.core.domain.AjaxResult.Companion.success
import com.ruoyi.common.utils.MessageUtils.message
import com.ruoyi.common.utils.MyStringUtils
import com.ruoyi.common.utils.ServletUtils.renderString
import com.ruoyi.framework.manager.AsyncManager.Companion.me
import com.ruoyi.framework.manager.factory.AsyncFactory.recordLogininfor
import com.ruoyi.framework.web.service.TokenService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation.Configuration
import org.springframework.security.core.Authentication
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler
import java.io.IOException
import javax.servlet.ServletException
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 * 自定义退出处理类 返回成功
 *
 * @author ruoyi
 */
@Configuration
open class LogoutSuccessHandlerImpl : LogoutSuccessHandler {
    @Autowired
    private lateinit var tokenService: TokenService

    /**
     * 退出处理
     *
     * @return
     */
    @Throws(IOException::class, ServletException::class)
    override fun onLogoutSuccess(request: HttpServletRequest, response: HttpServletResponse, authentication: Authentication?) {
        val loginUser = tokenService.getLoginUser(request)
        if (MyStringUtils.isNotNull(loginUser)) {
            val userName = loginUser?.username
            // 删除用户缓存记录
            tokenService.delLoginUser(loginUser?.token)
            // 记录用户退出日志
            me().execute(recordLogininfor(userName, Constants.LOGOUT, message("user.logout.success")))
        }
        renderString(response, JSON.toJSONString(success(message("user.logout.success"))))
    }
}
